from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.forms import ModelForm
from django.shortcuts import render, redirect
from django import forms
from django.utils.safestring import mark_safe

from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.bootstrap import BootstrapModelForm




def num_list(request):
    """靓号列表"""

    # page_now = int(request.GET.get('page', 1))
    #
    # page_range = 5  # 当前页面前后留几个页码
    # start = (page_now - 1) * 10
    # end = page_now * 10 + 2
    #
    # # 总数据行数
    # data_num = models.PrettyNum.objects.all().count()
    #
    # # 总页码
    # page_num, div = divmod(data_num, 10)
    # if div:
    #     page_num += 1
    #
    # page_show = 5
    # # 如果总页码数量大于 11
    # if page_num > page_show * 2 + 1:
    #     # 如果当前页面页码位置小于等于5
    #     if page_now <= 5:
    #         start_page = 1
    #         end_page = page_show * 2 + 2
    #     # 否则,当前页面页码位置大于5时
    #     else:
    #         # 防止页码超出范围
    #         if page_now >= page_num - page_show:
    #             start_page = page_num - page_show * 2
    #             end_page = page_num + 1
    #         else:
    #             # 计算出当前页的前5页和后5页
    #             start_page = page_now - page_show
    #             end_page = page_now + page_show + 1
    #
    # else:
    #     start_page = 1
    #     end_page = page_num + 1
    #
    # ######## 创建页码 ########
    # # 页码
    # page_str_list = []
    #
    # # 跳到首页
    # head_page = '?page={}'.format(1)
    #
    # # 跳到上10页
    # # 如果当前页面小于 11, 防止超过最小页数
    # if page_now < page_show * 2 + 1:
    #     prev = '<li><a href="?page={}">{}</a></li>'.format(1, "<<")
    #     page_str_list.append(prev)
    # else:
    #     prev = '<li><a href="?page={}">{}</a></li>'.format(page_now - 10, "<<")
    #     page_str_list.append(prev)
    #
    # for i in range(start_page, end_page):
    #
    #     # 如果是当前页,高亮显示页码颜色
    #     if page_now == i:
    #         ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
    #     else:
    #         ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
    #     page_str_list.append(ele)
    #
    # ### 跳到下10页
    # # 如果当前页面页数 大于 最大页面数量减去(page_show*2+1),则直接跳到最后一页,防止超过最大页数
    # if page_now >= page_num - page_show * 2 + 1:
    #     next = '<li><a href="?page={}">{}</a></li>'.format(page_num, ">>")
    #     page_str_list.append(next)
    # else:
    #     next = '<li><a href="?page={}">{}</a></li>'.format(page_now + 10, ">>")
    #     page_str_list.append(next)
    #
    # page_string = mark_safe("".join(page_str_list))
    #
    # # 跳到尾页
    # end_page = '?page={}'.format(page_num)
    #
    # ################### 代码实现分页结束 ###################
    #





    data_dict = {}

    search_data = request.GET.get('query', "")  # 不加后面的 "", 首次访问浏览器,搜索框中不会显示前端页面中的 placeholder="Search for..." 属性
    if search_data:
        data_dict["mobile__contains"] = search_data

    num_data = models.PrettyNum.objects.filter(**data_dict).order_by("id")


#################分页代码#########


    page_object = Pagination(request, num_data, page_size=10, page_param="page")
    page_queryset = page_object.page_queryset

    # 调用对象的html方法,生成页码
    page_object.html()

    page_string = page_object.page_string
    head_page = page_object.head_page
    end_page = page_object.end_page

    context = {
        "num_data": page_queryset,  # 分页的数据
        "search_data": search_data,  # 搜索的内容
        "page_string": page_string,  # 页码
        "head_page": head_page,  # 首页
        "end_page": end_page,  # 尾页
    }

    return render(request, "num_list.html", context)


    # 加入search_data的目的是,当搜索后,搜索框内的值不会置为空
    #return render(request, "num_list.html", {"num_data": num_data, "search_data": search_data})


def num_del(request):
    """删除"""
    if request.method == 'GET':
        nid=request.GET.get("nid")
        models.PrettyNum.objects.filter(id=nid).delete()
        return redirect("/num/list/")





class NumModelForm(forms.ModelForm):
    def clean_mobile(self):
        txt_mobile = self.cleaned_data['mobile']

        if len(txt_mobile) != 11:
            # 验证不通过
            raise ValidationError('格式错误')

        # 验证通过
        return txt_mobile




    class Meta:
        model = models.PrettyNum
        fields = ['mobile','price','status','level']
        # widgets = {
        # "name": forms.TextInput(attrs={"class": "form-control", "placeholder": ""})
        # }
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name,field in self.fields.items():
            field.widget.attrs={"class" :"form-control"}



from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=models.PrettyNum)
def update_id(sender, instance, **kwargs):
    if instance.id is None:
        last_id = models.PrettyNum.objects.all().order_by('-id').first().id
        instance.id = last_id + 1 if last_id else 1
def num_add(request):
    """添加"""
    if request.method == "GET":
        form=NumModelForm()
        return render(request, "num_add.html",{"form":form})

    #数据效验
    form=NumModelForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect("/num/list")

    return render(request, "num_add.html", {"form": form})


class PrettyEditModelForm(forms.ModelForm):
    mobile=forms.CharField(disabled=True,label="手机号")
    class Meta:
        model = models.PrettyNum
        # fields = "__all__"    表示取表中所有的字段
        fields = ['mobile','price', 'level', 'status']
        # exclude = ['level']   表示取除了表中的某个字段的所有字段

    # 循环找到所有的插件,加入css样式,添加 "class": "form-control"
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            print(name, field)
            field.widget.attrs = {"class": "form-control"}




def num_edit(request,id):
    """用户编辑"""
    row_object=models.PrettyNum.objects.filter(id=id).first()
    if request.method == "GET":


        form = NumModelForm(instance=row_object)



        return render(request, "num_edit.html",{"id":id,"form":form})



    form=NumModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/num/list/")
    else:
        print(form.errors)
        return render("num_edit.html", {"form":form})

